var search = location.search
var arr = /id=(\d+)/.exec(search)


if (!arr) {
  layer.msg('非法请求', {
    icon: 2,
    time: 1500
  }, function () {
    location.href = 'shop-list.html'
  })
}

var id = arr[1]
var loadindex = layer.load(0, {
  shade: [1, '#fff']
})

$.post('./php/shop.php', { id }, res => {
  layer.close(loadindex)
  var { meta: { status, msg }, data } = res
  console.log(res);
  console.log(data);
  if (status == 1) {
    var smallImgs = data[0].imgpath.split('=====')
    var img = ''
    smallImgs.forEach((item, index) => {
      if (index == 0) {
        $(".goodsname span").text(data[0].name)
        $(".goodsprice span").text(data[0].price)
        $(".goodsintroduce p").text(data[0].introduce)
        img += `<img class="active" src="${item}">`

        $('.zhong>img').attr('src', item)
        $('.big>img').attr('src', item)
      } else {
        img += `<img src="${item}">`
      }
    });
    $(".small").html(img)

    enlarge()


    addCar()
  }

}, 'json')


// 添加购物车
function addCar() {
  $(".add-shop-car").click(function () {
    if (!username) {
      layer.msg('请先登录', {
        icon: 2,
        time: 1500
      }, function () {
        localStorage.setItem('url', location.href)
        location.href = 'denglu.html'
      })

      return false
    }
    var data = localStorage.getItem('data')
    if (data) {
      var arr = JSON.parse(data)
      var obj = arr.find(item => item.username == username && item.id == id)
      if (obj) {
        obj.number += 1
      }
      else {
        obj = {
          username: username,
          id: id,
          number: 1
        }
        arr.push(obj)
      }
    } else {
      var arr = [{
        username: username,
        id: id,
        number: 1
      }]
    }

    localStorage.setItem('data', JSON.stringify(arr))

  })
}



$("#zuce-button").click(function () {
  if ($("#zuce-button").text() == '退出') {
    removeCookie('username')
    $('.denglu-button').html(`<a href="./denglu.html">登录</a>`)
    $('#zuce-button').html(`<a href="">注册</a>`)
    location.reload()
  }
})
